package com.password;

import java.security.MessageDigest;

public class Encrypt {
	/**
	 * convert string to md5_string
	 * @param str
	 * @return
	 */
	public static String getMD5String(String str) {
		byte[] b=str.getBytes();
		return getMD5String(b);
	}
	/**
	 * Gets the MD5 hash of the given byte array.
	 * 
	 * @param b
	 *            byte array for which an MD5 hash is desired.
	 * @return 32-character hex representation the data's MD5 hash.
	 */
	public static String getMD5String(byte[] b) {
		String javaPackageMD5 = "";
		try {
			byte[] javaDigest = MessageDigest.getInstance("MD5").digest(b);
			javaPackageMD5 = toHex(javaDigest);
		} catch (Exception ex) {
		}
		return javaPackageMD5;
	}
	
	/**
	 * Turns array of bytes into string representing each byte as a two digit
	 * unsigned hex number.
	 * 
	 * @param hash
	 *            Array of bytes to convert to hex-string
	 * @return Generated hex string
	 */
	private static String toHex(byte hash[]) {
		StringBuffer buf = new StringBuffer(hash.length * 2);
		for (int i = 0; i < hash.length; i++) {
			int intVal = hash[i] & 0xff;
			if (intVal < 0x10) {
				// append a zero before a one digit hex
				// number to make it two digits.
				buf.append("0");
			}
			buf.append(Integer.toHexString(intVal));
		}
		return buf.toString();
	}
}
